#!/bin/bash

set -e
set -x

iplist_path=config
master_ip=$(grep master $iplist_path | awk -F, '{printf $2}')
cp sentinel.conf.tpl sentinel.conf
sed -i "s/(master_ip)/$master_ip/" sentinel.conf
vip=$(grep vip $iplist_path | awk -F= '{printf $2}')
cp reconfig.sh.tpl reconfig.sh
sed -i "s/(vip)/$vip/" reconfig.sh
while read -r line
do
    case $line in
        *'#'*)
            continue
        ;;
        *'end'*)
            break
        ;;
        *)
            IFS=',' read -ra parts <<< "$line"
        ;;
    esac
    
    pass="${parts[0]}" 
    address="${parts[1]}"
    hostname="${parts[2]}"
    flag="${parts[3]}"
    
    if [ $address ];then
        if [ $flag = "master" ];then
            sshpass -p$pass ssh -n $address ifconfig ens33:0 $vip/24  
        fi
        sshpass -p$pass scp sentinel.conf $address:/usr/local/redis/conf/sentinel.conf
        sshpass -p$pass scp reconfig.sh $address:/usr/local/redis/reconfig.sh
        sshpass -p$pass ssh -n $address chmod +x /usr/local/redis/reconfig.sh
        sshpass -p$pass ssh -n $address chown -R redis.redis /usr/local/redis/
        sshpass -p$pass scp sentinel.service $address:/usr/lib/systemd/system/
        sshpass -p$pass ssh -n $address systemctl daemon-reload
        sshpass -p$pass ssh -n $address systemctl enable --now sentinel
    fi
    
done < $iplist_path

set +x
set +e